package com.yyaccp.itrip.utils;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 天天向上 （john.yi@qq.com）
 * @date 2020/11/16.
 */
public class RedisAPI {
    private JedisPool jedisPool;

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public void set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
    }

    public void del(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
    }
    public Long ttl(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.ttl(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
        return -1L;
    }
    public void setex(String key,int seconds, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.setex(key, seconds, value);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
    }

    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            returnResource(jedisPool, jedis);
        }
        return null;
    }

    public static void returnResource(JedisPool pool,Jedis redis){
        if(redis != null){
            pool.returnResource(redis);
        }
    }
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1");
        jedis.setex("code", 300, "12345");
        Map<String, Object> obj = new HashMap<>();
        obj.put("username","zs");
        obj.put("age", 18);
        jedis.set("user", JSONObject.toJSONString(obj));

        String json = jedis.get("user");
        Map map = JSONObject.parseObject(json, Map.class);
        System.out.println(map);

        jedis.lpush("list1", "1", "2", "3");
        jedis.sadd("set1", "a", "b", "b", "c");
    }
}
